#include <linux/types.h>
#include <linux/kdev_t.h>
#include <linux/cdev.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/fcntl.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include "hello_proc2.h"
struct jihaixuan jihaixuan_stru = {
    .no_useage = 0,
    .index = 0,
};
ssize_t jihaixuan_write (struct file * f, const char __user * buf, size_t buf_count, loff_t * f_pos){
    printk(KERN_INFO "jihaixuan_write count %ld\n",buf_count);
    if(buf_count!=1){
        return -EFAULT;
    }
    if (copy_from_user(&jihaixuan_stru.no_useage,buf,buf_count)!=0){
        return -EFAULT;
    }
    if (jihaixuan_stru.no_useage >= '0' && jihaixuan_stru.no_useage<='9'){
        jihaixuan_stru.index = jihaixuan_stru.no_useage-'0';
    }
    return buf_count;
};
void * jihaixuan_start (struct seq_file *m, loff_t *pos){
    printk(KERN_INFO "jihaixuan_start pos %lld\n",*pos);
    printk(KERN_INFO "jihaixuan_start index %d\n",jihaixuan_stru.index);
    if(jihaixuan_stru.index>=10){
        return NULL;
    }
    
    return &jihaixuan_stru.no_useage;
};
void jihaixuan_stop (struct seq_file *m, void *v){

};
void * jihaixuan_next (struct seq_file *m, void *v, loff_t *pos){
    printk(KERN_INFO "jihaixuan_next pos %lld\n",*pos);
    printk(KERN_INFO "jihaixuan_next index %d\n",jihaixuan_stru.index);
    (*pos)++;
    jihaixuan_stru.index++;
    if(jihaixuan_stru.index>=10){
        return NULL;
    }
    
    return &jihaixuan_stru.no_useage;
};
int jihaixuan_show (struct seq_file *m, void *v){
    seq_printf(m,"index %d nousage %d\n",jihaixuan_stru.index,jihaixuan_stru.no_useage);
    return 0;
};
struct seq_operations jihaixuan_seq_ops = {
    .next = jihaixuan_next,
    .show = jihaixuan_show,
    .start = jihaixuan_start,
    .stop = jihaixuan_stop,
};
int jihaixuan_open(struct inode *i_n, struct file *f)
{
    int err = seq_open(f, &jihaixuan_seq_ops);
    printk(KERN_INFO "jihaixuan_open %d\n", err);
    return err;
};
static struct proc_ops jihaixuan_ops = {
    .proc_read = seq_read,
    .proc_write = jihaixuan_write,
    .proc_release = seq_release,
    .proc_lseek = seq_lseek,
    .proc_open = jihaixuan_open,
};




static int __init init_function(void)
{
    proc_create("jihaixuan", S_IRUSR|S_IWUSR|S_IRGRP, NULL, &jihaixuan_ops);
    printk(KERN_INFO "jihaixuan init success\n");
    return 0;
}
static void __exit exit_function(void)
{
    remove_proc_entry("jihaixuan",NULL);
    printk(KERN_INFO "jihaixuan bye\n");
}

module_init(init_function);
module_exit(exit_function);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("jihaixuan");